import java.util.PriorityQueue;
import java.util.TimerTask;

//模拟实现定时器

class MyTimerTask implements Comparable<MyTimerTask>{
    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public Runnable getRunnable() {
        return this.runnable;
    }

    public long getTime() {
        return this.time;
    }
}

class MyTimer {
    PriorityQueue<MyTimerTask> priorityQueue = new PriorityQueue<>();
    Object locker = new Object();

    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            priorityQueue.offer(new MyTimerTask(runnable,delay));
            locker.notify();
        }
    }

    public MyTimer() {
        Thread thread = new Thread(() -> {
            try {
                synchronized (locker) {
                    while (true) {
                        while (priorityQueue.isEmpty()) {
                            locker.wait();
                        }

                        MyTimerTask peek = priorityQueue.peek();
                        long currTime = System.currentTimeMillis();

                        if (currTime >= peek.getTime()) {
                            peek.getRunnable().run();
                        } else {
                            locker.wait();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        thread.start();
    }
}

public class TimerExample {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();

        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
    }
}